package com.dynamic.sync.toolkit.mysql.sync.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dynamic.sync.toolkit.mysql.sync.po.BasePo;
import java.io.Serializable;
import java.util.List;
import java.util.function.Consumer;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ZonLen since on 2021/6/19 下午11:42
 */
public abstract class TemplateRepository<R extends BasePo> {

  @Autowired
  private BaseMapper<R> baseMapper;

  public List<R> loadConditionByList(Class<R> rClass, Consumer<LambdaQueryWrapper<R>> consumer) {
    final LambdaQueryWrapper<R> queryWrapper = new LambdaQueryWrapper<>();
    consumer.accept(queryWrapper);
    return baseMapper.selectList(queryWrapper);
  }

  public R loadOneById(Serializable id) {
    return baseMapper.selectById(id);
  }

  public void ifExistDelById(Serializable id) {
    if (null != loadOneById(id)) {
      deleteById(id);
    }
  }

  public void ifNotExistInsert(R r) {
    if (null == loadOneById(r.getId())) {
      insertOne(r);
    } else {
      update(r);
    }
  }

  public void deleteById(Serializable id) {
    final int i = baseMapper.deleteById(id);
    if (1 != i) {
      throw new RuntimeException("删除失败！");
    }
  }

  public void insertOne(R r) {
    baseMapper.insert(r);
  }

  public void update(R r) {
    baseMapper.updateById(r);
  }


}
